﻿// ActionScript file
/**
 * 从swf文件的库中提取导出类
 * 
 * @USAGE: 
 * LibraryManager.getInstance().addLibClass(url,libNames);
 * LibraryManager.getInstance().addEventListener(Event.COMPLETE,classesLoaded);
 * function classLoaded(e:Event):void{
 * 		//entry point
 * }
 * url为swf文件地址
 * libNames为链接类的名称
 */
package org.nickro.project.utils
{
	import flash.display.Loader;
	import flash.display.LoaderInfo;
	import flash.errors.IOError;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.net.URLRequest;
	
	public class LibraryManager extends EventDispatcher
	{
		private var libs:Object = { };
		private var names:Array = [];
		private static var _instance:LibraryManager;
		private static var _allowInstance:Boolean
		private var _url:String;
		public function LibraryManager()
		{
			if(_allowInstance)
			{
				throw new Error("Error: Use SoundManager.getInstance() instead of the new keyword.");
			}
		}
		
		public static function getInstance():LibraryManager
		{
			if(_instance == null)
			{
				_allowInstance = false;
				_instance = new LibraryManager();
				_allowInstance = true;
			}
			return _instance;
		}
		
		public function addLibClass(url:String,libNames:Array):void
		{
			_url = url;
			names = libNames;
			var loader:Loader = new Loader();
			loader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS,onProgress);
			loader.contentLoaderInfo.addEventListener(Event.COMPLETE,onComplete);
			loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR,onIOError);
			loader.load(new URLRequest(url));
		}
		
		public function get libClasses():Object
		{
			return libs;
		}
		
		private function onProgress(e:ProgressEvent):void
		{
			
		}
		/**
		 * dispatchEvent(Event.COMPLETE);
		 */
		private function onComplete(e:Event):void
		{
			for(var i:int = 0;i<names.length ; i++)
			{
				try
				{
					
					var c:Class = (e.target as LoaderInfo).applicationDomain.getDefinition(names[i].toString()) as Class;
					libs[names[i]] = c;
				}catch(e:Error)
				{
					throw new Error(names[i].toString() + " is unexisted.");
				}
			}
			dispatchEvent(e.clone());
		}
		
		private function onIOError(e:IOErrorEvent):void
		{
			throw new IOError('"' + _url + '"'+ "is unexisted");
		}
	}
}